package com.dinggao.crossgo.module.user;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.dinggao.crossgo.R;
import com.dinggao.crossgo.core.base.BaseActivity;
import com.dinggao.crossgo.core.constant.CommonConstant;
import com.dinggao.crossgo.core.manage.ActivtyManager;
import com.dinggao.crossgo.core.manage.ApiManager;
import com.dinggao.crossgo.core.paser.FastJsonUtils;
import com.dinggao.crossgo.core.ui.SecurityCodeView;
import com.dinggao.crossgo.core.util.DeviceInfo;
import com.dinggao.crossgo.core.util.LogUtils;
import com.dinggao.crossgo.core.util.SharedPreferencesUtil;
import com.dinggao.crossgo.module.roadbook.activity.RoadBookPublishMainActivity;
import com.dinggao.crossgo.module.user.login.LoginResultBean;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;


public class IdentifyCodeActivity extends BaseActivity implements SecurityCodeView.InputCompleteListener {

    @BindView(R.id.code_edit)
    SecurityCodeView code_edit;
    @BindView(R.id.text_code)
    TextView textCode;
    @BindView(R.id.identify_phone)
    TextView identifyPhone;
    @BindView(R.id.iv_top_bar_left)
    ImageView ivTopBarLeft;
    @BindView(R.id.tv_top_bar_title)
    TextView tvTopBarTitle;

    private String phone = "18888888888";
    public static final String TAG = "IdentifyCodeActivity";

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_identifycode;
    }

    @Override
    protected void onInitialization(Bundle bundle) {


        tvTopBarTitle.setText("验证码");
        phone = getIntent().getStringExtra("phone");
        identifyPhone.setText(phone);

        startCountDown();
        code_edit.setInputCompleteListener(new SecurityCodeView.InputCompleteListener() {
            @Override
            public void inputComplete() {
                getLogin();
            }

            @Override
            public void deleteContent(boolean isDelete) {

            }
        });

    }

    private void startCountDown() {

        final int count = 60;//倒计时10秒
        Observable.interval(0, 1, TimeUnit.SECONDS)
                .take(count + 1)
                .map(new Function<Long, Long>() {
                    @Override
                    public Long apply(Long aLong) throws Exception {
                        return count - aLong;
                    }
                })

                .observeOn(AndroidSchedulers.mainThread())//ui线程中进行控件更新
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        textCode.setEnabled(false);
                        textCode.setTextColor(Color.GRAY);
                    }
                }).subscribe(new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Long num) {

                textCode.setText("重新获取(" + num + "s)");
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                //回复原来初始状态
                textCode.setEnabled(true);
                textCode.setTextColor(Color.BLACK);
                textCode.setText("点击重新获取");

            }
        });
    }


    private void getMessage() {
        OkGo.<String>get(ApiManager.SEND_MESSAGE)
                .params("phone", phone)
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Log.e(TAG, "onSuccess: " + response.body().toString());

//                        if (response.code()!=0){
//                            Toast.makeText(IdentifyCodeActivity.this, response.body().toString(), Toast.LENGTH_LONG).show();
//                        }


                    }

                    @Override
                    public void onError(Response<String> response) {
                        Log.e("TAG", "onError: " + response.getException().toString());

                    }
                });
    }

    private void getLogin() {

        OkGo.<String>post(ApiManager.AUTH_LOGIN)
                .params("phone", phone)
                .params("smsCode", code_edit.getEditContent())
                .params("deviceToken", DeviceInfo.getDeviceToken(IdentifyCodeActivity.this))
                .params("os", "android")
                .params("appVersion", DeviceInfo.getVersionCode(IdentifyCodeActivity.this))
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                        if (response.body() != null) {
                            LoginResultBean data = FastJsonUtils.getObject(response.body(), LoginResultBean.class);
                            Log.e("TAG", "onSuccess: " + response.body());
                            // 将Token记录到本地

                            if (data != null && data.getCode() == 0) {
                                SharedPreferencesUtil.setSharedPreferencesString(
                                        IdentifyCodeActivity.this,
                                        CommonConstant.USERINFO_SHREDPREFERENCE,
                                        CommonConstant.USRERINFO_SHRAREDPREFERCE_ACCESS_TOKEN,
                                        data.getData().getAccessToken());

                                SharedPreferencesUtil.setSharedPreferencesString(
                                        IdentifyCodeActivity.this,
                                        CommonConstant.USERINFO_SHREDPREFERENCE,
                                        CommonConstant.USERINFO_USERID,
                                        data.getData().getUserId() + "");

                                boolean useWEIXIN = SharedPreferencesUtil.getSharedPreferencesBoolean(IdentifyCodeActivity.this,
                                        CommonConstant.USERINFO_SHREDPREFERENCE, CommonConstant.USERINFO_USEWEIXIN);

                                if (!useWEIXIN) {
                                    //把头像的图标默认存进去
                                    SharedPreferencesUtil.setSharedPreferencesString(
                                            IdentifyCodeActivity.this,
                                            CommonConstant.USERINFO_SHREDPREFERENCE,
                                            CommonConstant.USERINFO_HEANDIMAGEURI,
                                            "logo");
                                }

                                // 跳转到首页
                                Intent intent = new Intent();
                                intent.setClass(IdentifyCodeActivity.this, RoadBookPublishMainActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                startActivity(intent);
                            } else {
                                Toast.makeText(IdentifyCodeActivity.this, data.getMessage(), Toast.LENGTH_LONG).show();
                                code_edit.clearEditText();
                            }

                        } else {

                            Toast.makeText(IdentifyCodeActivity.this, "验证码错误", Toast.LENGTH_LONG).show();
                            code_edit.clearEditText();
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        LogUtils.e(TAG, response.getException().toString());
                        Toast.makeText(IdentifyCodeActivity.this, "验证码错误", Toast.LENGTH_LONG).show();
                        code_edit.clearEditText();
                    }
                });
    }

    @Override
    public void inputComplete() {
        Toast.makeText(getApplicationContext(), "验证码是：" + code_edit.getEditContent(), Toast.LENGTH_LONG).show();
    }

    @Override
    public void deleteContent(boolean isDelete) {
        if (isDelete) {
            Toast.makeText(getApplicationContext(), "验证码是：" + code_edit.getEditContent(), Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.iv_top_bar_left, R.id.text_code})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_top_bar_left:
                ActivtyManager.getAppManager().finishActivity();
                break;
            case R.id.text_code:
                getMessage();
                startCountDown();
                break;
        }
    }


    @OnClick(R.id.tv_top_bar_title)
    public void onViewClicked() {
    }
}
